package com.quanshu.exchange.ui.gui.profile;

import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.GoodsEntity;
import com.quanshu.exchange.support.entity.ShoppingCarEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 购物车删除状态
 * Created by xiniu003 on 2018/2/1.
 */

public class ShopCartDeleteActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.edit_comment)
    TextView editComment;
    @BindView(R.id.shop_trolley_null)
    LinearLayout shopTrolleyNull;
    @BindView(R.id.shop_trolley_recy)
    RecyclerView shopTrolleyRecy;
    @BindView(R.id.shop_trolley_all_image)
    ImageView shopTrolleyAllImage;
    @BindView(R.id.shop_trolley_all_llt)
    LinearLayout shopTrolleyAllLlt;
    @BindView(R.id.shop_trolley_total_price)
    TextView shopTrolleyTotalPrice;
    @BindView(R.id.shop_trolley_zongji_llt)
    LinearLayout shopTrolleyZongjiLlt;
    @BindView(R.id.shop_trolley_delete)
    TextView shopTrolleyDelete;

    private SingleAdapter<GoodsEntity> adapter;
    private List<GoodsEntity> allDatas;
    private boolean isCheckAll = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_trolley);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());

        //删除
        RxViewHelper.getInstance().clicks(shopTrolleyDelete, aVoid -> {
            getRemoveCart();
        });

        //全选
        RxViewHelper.getInstance().clicks(shopTrolleyAllLlt, aVoid -> {
            doCheckAll();
        });
    }

    private void initView() {

        editComment.setVisibility(View.GONE);
        shopTrolleyZongjiLlt.setVisibility(View.GONE);
        shopTrolleyDelete.setText("删除");
        shopTrolleyRecy.setLayoutManager(new LinearLayoutManager(this));
        adapter = new SingleAdapter<>(new DataDisplayer<GoodsEntity>(this,
                R.layout.item_shop_trolley) {
            @Override
            public void bindData(BaseViewHolder holder,
                                 LayoutWrapper<GoodsEntity> wrapper,
                                 GoodsEntity item,
                                 int position) {

                item.setTwo_price(String.valueOf(Double.valueOf(item.getSell_price()) * 2));

                holder.setImageUrl(R.id.shop_trolley_shop_image,
                        Config.URL_HOST_SHOP + item.getImg(),
                        R.drawable.default_avatar);
                holder.setText(R.id.shop_trolley_shop_name, item.getName());
                holder.setText(R.id.shop_trolley_shop_bianhao, "商品编号：" + item.getGoods_no());
                holder.setText(R.id.shop_trolley_shop_price_j, item.getSell_price());
                holder.setText(R.id.shop_trolley_shop_price_r, "￥" + item.getSell_price());
                TextView shopPriceR = holder.getView(R.id.shop_trolley_shop_price_r);
                shopPriceR.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                holder.setText(R.id.shop_trolley_shop_number, "x" + item.getCount());
                holder.getView(R.id.mianfei_select).setVisibility(View.GONE);
                ImageView imageView = holder.getView(R.id.shop_trolley_select_image);
                if (item.isSelectState()) {
                    imageView.setSelected(true);
                    for (GoodsEntity entity : allDatas) {
                        if (!entity.isSelectState()) {
                            isCheckAll = false;
                            shopTrolleyAllImage.setSelected(false);
                            break;
                        } else {
                            isCheckAll = true;
                            shopTrolleyAllImage.setSelected(true);
                        }
                    }
                } else {
                    imageView.setSelected(false);
                    isCheckAll = false;
                    shopTrolleyAllImage.setSelected(isCheckAll);
                }
                //只要有一个item处于勾选状态，“删除” 文字就高亮
                for (GoodsEntity entity : allDatas) {
                    if (entity.isSelectState()) {
                        shopTrolleyDelete.setBackgroundColor(Color.parseColor("#F8DCB0"));
                        break;
                    } else if (!entity.isSelectState()) {
                        shopTrolleyDelete.setBackgroundColor(Color.parseColor("#C8C8C8"));
                    }
                }
                //勾选商品
                holder.getView(R.id.all_shop_trolley).setOnClickListener(view -> {
                    if (item.isSelectState()) {
                        item.setSelectState(false);
                        isCheckAll = false;
                    } else {
                        item.setSelectState(true);
                    }
                    adapter.notifyDataSetChanged();
                });
            }
        });
        shopTrolleyRecy.setAdapter(adapter);
    }

    //全选
    private void doCheckAll() {
        if (adapter != null && allDatas != null && allDatas.size() > 0) {
            isCheckAll = !isCheckAll;
            shopTrolleyAllImage.setSelected(isCheckAll);
            for (GoodsEntity goodsEntity : allDatas) {
                if (isCheckAll == true) {
                    goodsEntity.setSelectState(true);
                } else {
                    goodsEntity.setSelectState(false);
                }
            }
            adapter.notifyDataSetChanged();
        }
    }

    private void initData() {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .getMyCart(AppUtils.getSignParams(String.valueOf(currentUser.getId())), String.valueOf(currentUser.getId()))
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<ShoppingCarEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<ShoppingCarEntity> response) {
                        if (response.getData() != null && response.getData().getGoodsList().size() > 0) {
                            shopTrolleyNull.setVisibility(View.GONE);
                            allDatas = response.getData().getGoodsList();
                            adapter.setData(allDatas);
                        } else {
                            shopTrolleyNull.setVisibility(View.VISIBLE);
                            shopTrolleyDelete.setBackgroundColor(Color.parseColor("#C8C8C8"));
                            shopTrolleyAllImage.setSelected(false);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    private String[] goodsIdArray;//商品一维数组

    //用于删除
    private final String[] getGoodsIdTypeArray() {
        ArrayList<String> goodsId = new ArrayList<String>();
        if (allDatas != null && allDatas.size() > 0) {
            for (GoodsEntity goodsEntity : allDatas) {
                if (goodsEntity.isSelectState()) {

                    if (goodsEntity.getGoods_type().equals("goods")) {
                        goodsId.add(goodsEntity.getGoods_id() + "," + goodsEntity.getGoods_type());
                    } else {
                        goodsId.add(goodsEntity.getProduct_id() + "," + goodsEntity.getGoods_type());
                    }
                }
            }
            goodsIdArray = goodsId.toArray(new String[goodsId.size()]);
        }
        return goodsIdArray;
    }

    //批量删除
    private void getRemoveCart() {
        //做删除操作时，须将String[]转为json字符串
        Gson gson = new Gson();
        String deleteString = gson.toJson(getGoodsIdTypeArray());

        Log.e("deleteString", deleteString);

        NetClient.getInstance().getShopService(ShopInterface.class)
                .doRemoveCart(AppUtils.getSignParams(String.valueOf(currentUser.getId()),
                        deleteString), String.valueOf(currentUser.getId()),
                        deleteString)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {

                        initView();
                        initData();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }
}
